package com.ym521.myktx

import android.util.Log
import com.ym521.myktx.utils.Base64
import java.math.BigInteger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

/**
 *@author Ym
 *E-mail: 2435970206@qq.com
 *createTime:2024/4/4
 *explain:
 *  关于String的转换，即使出现了异常
 */

fun String.toByte(default: Byte = 0): Byte {
    var v: Byte = default
    try {
        v = this.toByte()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }
    return v
}

fun String.toShort(default: Short = 0): Short {
    var v: Short = default
    try {
        v = this.toShort()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }

    return v
}

fun String.toInt(default: Int = 0): Int {
    var v: Int = default
    try {
        v = this.toInt()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }

    return v
}

fun String.toLong(default: Long = 0L): Long {
    var v: Long = default
    try {
        v = this.toLong()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }
    return v
}

fun String.toDouble(default: Double = 0.00): Double {
    var v: Double = default
    try {
        v = this.toDouble()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }

    return v
}

fun String.toFloat(default: Float = 0.0f): Float {
    var v: Float = default
    try {
        v = this.toFloat()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }
    return v
}


fun String.toBoolean(default: Boolean = false): Boolean {
    var v: Boolean = default
    try {
        v = this.toBoolean()
    } catch (e: Exception) {
        Log.e("StringExt", e.toString())
    }
    return v
}

fun String.toMD5(): String{
    try {
        val md = MessageDigest.getInstance("MD5")
        md.update(this.toByteArray()) //默认UTF-8
        // 完成计算并返回结果
        val digest = md.digest()
        val bigInt = BigInteger(1, digest)
        return String.format("%032x", bigInt)
    } catch (e: NoSuchAlgorithmException) {
        Log.e("String toMD5", e.toString())
    }
    throw Exception("String toMD5 has NoSuchAlgorithmException")
}

/**
 * Base64编码
 */
fun String.toBase64Encode(): String? {
    if (this.isEmpty()) return null
    return Base64.getEncoder().encodeToString(this.toByteArray(Charsets.UTF_8))
}

/**
 * Base64解码
 */
fun String.toBase64Decode(): String? {
    if (this.isEmpty()) return null
    return String(Base64.getDecoder().decode(this.toByteArray(Charsets.UTF_8)), Charsets.UTF_8)
}